import {demoImageListConfig} from './demoImageListConfig.js'
/** @type {HTMLCanvasElement} */
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
const colorEle = document.querySelector('#lincolor')
const linWidthEle = document.querySelector('#linwidth')
const pen = document.querySelector('.pen')
const xp = document.querySelector('.xiangpica')
const mode = document.querySelector('.mode') // 模式提示文本节点
const clearAll = document.querySelector('.clear-all') // 清除
const save = document.querySelector('.save') // 保存
let dialogEle = document.querySelector('.dialog') 


const cancel = document.querySelector('.cancel')
const confirm = document.querySelector('.confirm')

let utilEle = document.querySelector('.util')
let fadeIcon = document.querySelector('.fade-icon') // 收缩工具栏的图标节点
let fadeLeftRightEle = document.querySelector('.fade-left-right')
let fadeDone = false // 表示工具栏现在是否是贴边的状态
// 收缩工具栏函数
fadeLeftRightEle.addEventListener('click',() => {
    // 如果是贴边的状态
    if (fadeDone) {
        utilEle.classList.remove('fade-left')
        utilEle.classList.add('fade-right')
        fadeIcon.classList.remove('icon-xiayiyeqianjinchakangengduo')
        fadeIcon.classList.add('icon-shangyiyehoutuifanhui')
        fadeLeftRightEle.classList.remove('fade-bg')
    }else {
        utilEle.classList.remove('fade-right')
        utilEle.classList.add('fade-left')
        fadeIcon.classList.remove('icon-shangyiyehoutuifanhui')
        fadeIcon.classList.add('icon-xiayiyeqianjinchakangengduo')
        fadeLeftRightEle.classList.add('fade-bg')
    }
    fadeDone = !fadeDone
})


let fadeRightLeft = document.querySelector('.fade-right-left')
let rightFadeDone = false // 右侧的贴边状态
let rightFadeIcon = document.querySelector('.iconfont-right-i')
let domView = document.querySelector('.demo-view')
fadeRightLeft.addEventListener('click',()=>{
    // 如果是贴边的状态
    if (rightFadeDone) {
        domView.classList.remove('fade-right-dom-view')
        domView.classList.add('fade-left-dom-view')
        rightFadeIcon.classList.remove('icon-shangyiyehoutuifanhui')
        rightFadeIcon.classList.add('icon-xiayiyeqianjinchakangengduo')
        fadeRightLeft.classList.remove('fade-dom-view-bg')
    }else {
        domView.classList.remove('fade-left-dom-view')
        domView.classList.add('fade-right-dom-view')
        rightFadeIcon.classList.remove('icon-xiayiyeqianjinchakangengduo')
        rightFadeIcon.classList.add('icon-shangyiyehoutuifanhui')
        fadeRightLeft.classList.add('fade-dom-view-bg')
    }
    rightFadeDone = !rightFadeDone
})


// 换demo图片
let index = 0 // 记录当前随机照片的下标 防止下次随机生成相同 图片不会替换
let changeDemoImageButton = document.querySelector('.change-outher-btn')
let demoImage = document.querySelector('.demo-image')
let demoTitle = document.querySelector('.demo-title')
changeDemoImageButton.addEventListener('click',() => {
    let randomIndex = randomMath(0,demoImageListConfig.length-1)
    // 如果相同索引则+1
    randomIndex = randomIndex == index ? (randomIndex + 1 >= demoImageListConfig.length ? 0 : randomIndex + 1 ): randomIndex
    let randomImageObj = demoImageListConfig[randomIndex]
    index = randomIndex
    setDemoPath(randomImageObj)
})

// 设置demo图片路径
function setDemoPath (randomImageObj){
    demoImage.setAttribute('src',randomImageObj.path)
    demoTitle.innerText = randomImageObj.title
}
setDemoPath(demoImageListConfig[0]) // 第一次设置为0 索引为0记录


// 生成随机数
function randomMath(min,max){
    return Math.round(Math.random()*(max-min) + min)
}


// 开关弹窗函数
function switchDialog(status){
    if (status) {
        dialogEle.style.display = 'flex'
        dialogEle.classList.remove('animate__fadeInDown')
        dialogEle.classList.add('animate__fadeInDown')
    }else {
        dialogEle.style.display = 'none'
    }
}


let canTouch = false // 判断当前设备
let painting = false //控制划线的开关
let modeDone = 'draw' // 当前模式 draw - 画画 clear 橡皮擦
let cursorUrl = './images/black.ico'
let dialogDone = '' // 点击删除获取下载时候的判断标识

// animate__fadeInDown animate_fadeInUp

let lineColor = '#8A2BE2'
let lineConfig = {
    lineColor: '#8A2BE2',
    linWidth: linWidthEle.value / 20,
    cursonOffsetX: 10,
    cursonOffsetY: 16
}
// 修改颜色
colorEle.addEventListener('change', () => {
    lineConfig.lineColor = colorEle.value
})
// 修改粗细
linWidthEle.addEventListener('change', () => {
    lineConfig.linWidth = linWidthEle.value / 20
})
// 当前为画笔模式
pen.addEventListener('click', () => {
    modeDone = 'draw'
    updateDrawMode()
    updateModeTips('当前为画笔模式')
})
xp.addEventListener('click', () => {
    modeDone = 'clear'
    updateDrawMode()
    updateModeTips('当前为橡皮擦模式')
})

// 取消点击函数
cancel.addEventListener('click',() => {
    switchDialog(false)
})
// 确认点击函数
confirm.addEventListener('click',() => {
    if (dialogDone == 'clear'){
        ctx.clearRect(0,0,canvas.width,canvas.height)
    }else if (dialogDone == 'save'){
        saveCanvasImage()
    }
    switchDialog(false)
})


// 清理画布函数
clearAll.addEventListener('click',() => {
    dialogDone = 'clear'
    switchDialog(true)
})
// 保存画布
save.addEventListener('click',() => {
    dialogDone = 'save' 
    switchDialog(true)
})



// 保存画布画面处理函数
function saveCanvasImage(){
    let imgData = canvas.toDataURL()
    console.log('下载的照片文件',imgData);
    const el = document.createElement('a');
    // 设置 href 为图片经过 base64 编码后的字符串，默认为 png 格式
    el.href = imgData
    el.download = 'luox_canvas爱画图';
    const event = new MouseEvent('click');
    el.dispatchEvent(event);
}

// 模式更新下面的提示文本
function updateModeTips(tips) {
    mode.innerText = tips
}

// 修改当前绘画模式
function updateDrawMode() {
    switch (modeDone) {
        case 'draw':
            cursorUrl = './images/black.ico'
            break
        case 'clear':
            cursorUrl = './images/xiangpica.ico'
            break
    }
    updateCursor(cursorUrl)
}

// 修改当前指针样式
function updateCursor(cursorUrl) {
    canvas.style.cursor = `url('${cursorUrl}'),pointer`
}


function init() {
    let viewWidth = document.body.clientWidth
    let viewHeight = document.body.clientHeight
    canvas.width = viewWidth;
    canvas.height = viewHeight;
    // canvas.style.width = viewWidth
    if (document.body.ontouchstart !== undefined) {
        //触屏设备
        canTouch = true
    } else {
        //非触屏设备
        canTouch = false
    }
    bindEvent()
}
init()

let startPoint = { x: null, y: null }
function bindEvent() {
    if (canTouch) {
        canvas.ontouchstart = function (e) {
            //[0]表示touch第一个触碰点
            let x = e.touches[0].clientX - lineConfig.cursonOffsetX
            let y = e.touches[0].clientY - lineConfig.cursonOffsetY
            painting = true;
            startPoint = { x: x, y: y };
        };
        canvas.ontouchmove = function (e) {
            let x = e.touches[0].clientX - lineConfig.cursonOffsetX
            let y = e.touches[0].clientY - lineConfig.cursonOffsetY
            let newPoint = { x: x, y: y };
            if (painting) {
                if (modeDone === 'clear') {
                    clearPoint(startPoint, newPoint)
                    startPoint = newPoint
                } else if (modeDone === 'draw') {
                    drawLine(startPoint, newPoint);
                    startPoint = newPoint;
                }
            }
        };
        canvas.ontouchend = function () {
            painting = false;
        };
    } else {
        // 非触屏设备
        canvas.addEventListener('mousedown', (e) => {
            // console.log('e', e);
            let x = e.offsetX + 12
            let y = e.offsetY + lineConfig.cursonOffsetY
            painting = true;
            startPoint = { x, y }
        })

        canvas.addEventListener('mousemove', (e) => {
            let x = e.offsetX + lineConfig.cursonOffsetX
            let y = e.offsetY + lineConfig.cursonOffsetY
            let newPoint = { x, y }
            if (painting) {
                // 如果画笔为橡皮擦
                if (modeDone === 'clear') {
                    clearPoint(startPoint, newPoint)
                    startPoint = newPoint
                } else if (modeDone === 'draw') {
                    drawLine(startPoint, newPoint)
                    // console.log(e);
                    startPoint = newPoint
                }
            }
        })

        canvas.addEventListener('mouseup', (e) => {
            painting = false
        })
    }
}

// 判断鼠标移动
function drawLine(startPoint, newPoint) {
    ctx.strokeStyle = lineConfig.lineColor
    ctx.lineWidth = lineConfig.linWidth
    ctx.beginPath();
    ctx.moveTo(startPoint.x, startPoint.y);
    ctx.lineTo(newPoint.x, newPoint.y);
    ctx.stroke();
}

// 擦除
function clearPoint(startPoint, newPoint) {
    // ctx.clearRect(startPoint.x, startPoint.y, 12, 12) // 矩形删除
    clearArcFun(startPoint.x,startPoint.y,12,ctx) // 圆形删除
}

function clearArcFun(x, y, r, cxt) {    //(x,y)为要清除的圆的圆心，r为半径，cxt为context
    var stepClear = 1;
    clearArc(x, y, r);
    function clearArc(x, y, radius) {
        var calcWidth = radius - stepClear;
        var calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);
        var posX = x - calcWidth;
        var posY = y - calcHeight;

        var widthX = 2 * calcWidth;
        var heightY = 2 * calcHeight;

        if (stepClear <= radius) {
            cxt.clearRect(posX, posY, widthX, heightY);
            stepClear += 1;
            clearArc(x, y, radius);
        }
    }
}